#include "dbtabsettings.h"
#include "database/databasequery.h"

QMap<QString,DBTabSettings*> DBTabSettings::mDBMap;

const QString DBTabSettings::SETTING_DB_NAME = "setings.db";
const QString DBTabSettings::_KEY = "set_key";
const QString DBTabSettings::_VALUE = "set_value";
QSqlDatabase DBTabSettings::mDb;

void DBTabSettings::createTab(void)
{
    DataBaseQuery query(mDb,false);
    query.exec("drop table " + mTabName);
    QString str = "CREATE TABLE "+mTabName +"(\n" +
            _KEY + " varchar(64) primary key ,-- 信息名称\n" +
            _VALUE + " varchar(64)-- 信息值\n" +
            ") -- 数据库信息表\n";

    if(query.exec(str)==false)
    {
         qDebug()<<" create " +  mTabName + " error:\n "<<str;
    }
    query.createIndex(mTabName,_KEY);

}

QVariant DBTabSettings::getValue(const QString &key,const QVariant &def)
{
    DataBaseQuery query(mDb);
    QString str = "select "+_VALUE + " from "+ mTabName +" where " +  _KEY + " = '" +key+ "'";qDebug()<<str;
    query.exec(str);

    if(query.first())
    {
        return query.value(0).toString();
    }
    return def;
}

void DBTabSettings::setValue(const QString &key, const QVariant &value)
{
    DataBaseQuery query(mDb);
    QStringList keyList;
    keyList.append(_KEY);
    QString option = _KEY +"='" + key+"'";
    QMap<QString,QVariant> map;
    map.insert(_KEY,key);
    map.insert(_VALUE,value);
    if(query.selectTable(mTabName,&keyList,option))
    {
        if(query.first()){
            query.updateItem(mTabName,map,option);
        }else{
            query.insert(mTabName,map);
        }
    }
}


int DBTabSettings::getMaxIndex(const QString &key)
{
    DataBaseQuery query(mDb);

    QString str = "select max(substr("+_KEY+","+QString::number(key.length()+2)+",4)) from "+ mTabName +" where " +  _KEY + " like '" +key+ "'";
    if(query.exec(str))
    {
        return query.size();
    }
    return 0;
}

DBTabSettings::DBTabSettings(const QString &tabName):mTabName(tabName)
{
    if(mDb.tables().contains(tabName)==false)
        createTab();
}
